import 'package:file_picker/file_picker.dart';
import 'package:get/get.dart';
import 'package:safetymonitor/app/components/custom_modele/common_selection/common_selection_view.dart';
import 'package:safetymonitor/app/components/custom_modele/custom_file_upload_page.dart';
import 'package:safetymonitor/app/components/custom_modele/custom_high_input_page.dart';
import 'package:safetymonitor/app/components/custom_modele/custom_multiple_bottom_sheet.dart';
import 'package:safetymonitor/app/components/custom_modele/custom_select_page.dart';
import 'package:safetymonitor/app/components/custom_refresh.dart';
import 'package:safetymonitor/app/components/dialog/common_adaptive.dart';
import 'package:safetymonitor/app/components/toast_widget.dart';
import 'package:safetymonitor/app/core/core.dart';
import 'package:safetymonitor/app/core/ext/ext.dart';
import 'package:safetymonitor/app/core/http/http.dart';
import 'package:safetymonitor/app/core/utils/interface.dart';
import 'package:safetymonitor/app/core/utils/user_manager.dart';
import 'package:safetymonitor/app/data/entities/application/corporation_name_entity.dart';
import 'package:safetymonitor/app/data/entities/application/department_user_entity.dart';
import 'package:safetymonitor/app/data/entities/home/duty/system_user_page_entity.dart';
import 'package:safetymonitor/app/data/entities/home/warning/alarm_resp_entity.dart';
import 'package:safetymonitor/app/data/entities/home/warning/get_by_alarm_id_entity.dart';
import 'package:safetymonitor/router/app_pages.dart';
///今日警情
class TodayController extends GetxController {
  /// （登陆人id）
  int? latestDistributionHighId = UserManager.getUser()!.id;

  //------------------------督办-----------------------------------
  /// 现场处理人
  int? onSiteHandlerId;
  String onSiteHandlerName = '';
  /// 督办的记录 默认空的
  List<GetByAlarmIdEntity>  supervisionRecord=[];
  //------------------------派发-----------------------------------
  ///  处置人
  String affiliateCompanyAssignHighId = '';
  String affiliateCompanyAssignHighIdName = '';

  /// 所属部门
  String departmentBelongsId = '';
  String departmentBelongsIdName = '';

  //------------------------处置-----------------------------------
  ///报警原因
  String reasonAlarm = '';

  /// 处置措施
  String alarmDescription = '';

  /// 现场处理时间
  String onSiteProcessingTime = '';

  /// 处置措施
  String disposalMeasures = '';

  /// 处置附件
  String disposalAttachments = '';

  /// 列表刷新key
  final GlobalKey<CustomEasyRefreshListState> globalKey = GlobalKey();

  List<AlarmRespEntity>? list = [];
  /// 获取数据
  Future<List<AlarmRespEntity>> theFeignEmergencyPlansPage(int index, int size, {String? search}) async {
    final res = await HttpUtil().generateGetRequest<List<AlarmRespEntity>>(
      Interface.getRecentAlarmMonitoring,
      queryParameters: {
        'pageNo': index,
        'pageSize': 5000,
      },
    ).execute();
    res.onSuccess((result) {
      if (result.data != null) {
        list = result.data;
      }
    });
    return list??[];
  }


  void refreshPage() {
    globalKey.currentState?.onRefresh();
  }
  /// 提交信息时的提示 1、督办派发 2、督办处置 3、派发 0、无操作按钮权限
  bool appToastTip(String supervisionStatusStr) {
    if (supervisionStatusStr == '1' || supervisionStatusStr == '2') {
      //督办
      if (onSiteHandlerName.isEmpty) {
        AppToast.show('请选择督办对象');
        return false;
      }
    } else if (supervisionStatusStr == '3') {
      //派发
      if (departmentBelongsId.isEmpty) {
        AppToast.show('请选择处置人部门');
        return false;
      }
      if (affiliateCompanyAssignHighId.isEmpty) {
        AppToast.show('请选择处置人');
        return false;
      }
    }else if (supervisionStatusStr == '4') {
      //派发
      if (reasonAlarm.trim().isEmpty) {
        AppToast.show('请输入报警原因');
        return false;
      }
      if (alarmDescription.trim().isEmpty) {
        AppToast.show('请输入处置措施');
        return false;
      }
    }
    return true;
  }

  /// 调接口去督办 /system/alarm-supervise-info/create
  void alarmSuperviseInfoCreate(AlarmRespEntity item,{bool closeOverlays=false}) async {
    if (!appToastTip(item.supervisionStatusStr)) {
      return;
    }
    if (item.supervisionStatusStr == '1' || item.supervisionStatusStr == '2') {
      // 调用接口
      final res = await HttpUtil()
          .generatePostRequest(
        Interface.createAlarmSupervise, // new督办接口  old派发处置接口
        data: _requestData(item),
      )
          .execute(isShowLoading: true);
      res.onSuccess((result) {
        Get.back();
        AppToast.showSuccess('提交成功');
        Get.find<TodayController>().globalKey.currentState?.onRefresh();
      });
    } else {
      // 调用接口
      final res = await HttpUtil()
          .generatePutRequest(
        Interface.alarmUpdate, // new督办接口  old派发处置接口
        data: _requestData(item),
      )
          .execute(isShowLoading: true);
      res.onSuccess((result) {
        Get.back(closeOverlays: closeOverlays );
        AppToast.showSuccess('提交成功');
        Get.find<TodayController>().globalKey.currentState?.onRefresh();
      });
    }
  }
  ///请求数据
  dynamic _requestData(AlarmRespEntity item) {
    if (item.supervisionStatusStr == '1' || item.supervisionStatusStr == '2') {
      //督办
      return {
        'companyId': item.companyId, //公司id
        'systemId': item.systemId, //系统id
        'alarmId': item.id, //报警预警id
        'superviseUserId': UserManager.getUser()?.id, //督办人id
        'superviseUserName': UserManager.getUser()?.nickname, //督办人名称
        'superviseType': item.supervisionStatusStr, //督办类型(1.指派2.处置)
        'superviseObjId': onSiteHandlerId, //督办对象id
        // 'superviseStatus': '',//督办状态(1.已读2.未读)
      };
    } else if (item.supervisionStatusStr == '3') {
      //派发 用老版本的接口
      return {
        'id': item.id,
        'click': 3,
        'latestOperationStatus': '2',
        'latestDistributionId': latestDistributionHighId, // 分公司派发人id（登陆人id）
        'latestDisposalId': affiliateCompanyAssignHighId, // 处置人id
        // 'undertakePersonId': affiliateCompanyAssignHighId, // 处置人id
      };
    } else if (item.supervisionStatusStr == '4') {
      //处置 用老版本的接口
      chuZhiConfirm(item);
      return {
        'id': item.id,
        'click': 5,
        'latestOperationStatus': '8',
        'latestDisposalId': latestDistributionHighId, //处置人id 也是登陆人
        'alarmLevel': item.alarmLevel,

        'sceneDisposalPersonId': latestDistributionHighId, //现场处理人
        'ascriptionDeptId': UserManager.getUser()!.dept.id, //所属部门
        'sceneDisposalTime': onSiteProcessingTime, //现场处理时间
        'sceneDisposalTimeStr': onSiteProcessingTime, //现场处理时间
        // 'undertakePersonId': latestDistributionHighId, //负责人
        'alarmStartTime': item.alarmStartTime, //报警开始时间 新增

        //新增字段（记录原因）老接口合并参数
        'reasonType': reasonAlarm, //处置报警原因类型
        'reasonAnalysis': alarmDescription, //处置报警原因分析
        'disposalMeasures': disposalMeasures, // 处置措施
        'disposalMeasuresAnnex': disposalAttachments, //  处置措施附件

        'dataType': item.dataType==0?'': item.dataType,
      };
    }
  }
  ///督办记录
  void getByAlarmId(int id) async {
    final res = await HttpUtil().generateGetRequest<List<GetByAlarmIdEntity>>(
      Interface.getByAlarmId,
      queryParameters: {'id': id},
    ).execute();
    res.onSuccess((result) {
      if (result.data != null) {
        supervisionRecord= result.data!;
      }
      update();
    });
  }
  ///是否全部显示
  bool  isAllRecord=true;
  /// 弹窗提示 1、督办派发 2、督办处置 3、派发 0、无操作按钮权限
  void onClickOperateDialog( AlarmRespEntity item,{bool closeOverlays=false}) {
    //重置
    isAllRecord=true;
    onSiteHandlerName='';
    onSiteHandlerId=0;
    affiliateCompanyAssignHighIdName='';
    affiliateCompanyAssignHighId='';
    departmentBelongsIdName='';
    departmentBelongsId='';
    reasonAlarm='';
    alarmDescription='';
    onSiteProcessingTime='';
    disposalMeasures='';
    disposalAttachments='';
    if (item.supervisionStatusStr == '1'||item.supervisionStatusStr == '2') {
      //查询督办记录
      getByAlarmId(item.id);
      // if (false) {
      // 弹窗提示
      Get.dialog<bool>(CommonAdaptiveDialog(
        title: '督办',
        contentWidget:
        GetBuilder<TodayController>(
            builder: (controller) {
              return Column(
                children: [
                  Visibility(
                    visible: supervisionRecord.isNotEmpty,
                    child:Column(children: [
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Text('督办记录',
                            style: TextStyle(
                                color: const Color(0xFF1D3452),
                                fontSize: 16.sp,
                                fontWeight: FontWeight.w400),
                          ),
                          Container(
                            padding: EdgeInsets.only(left: 4.w,top: 2.w,right: 4.w,bottom: 2.w),
                            decoration: BoxDecoration(
                              color: const Color(0xff2267C0),
                              borderRadius: BorderRadius.circular(4.w),
                            ),
                            child: Text(isAllRecord?'全部记录':'部分记录',
                              style: TextStyle(
                                  color: Colors.white,
                                  fontSize: 16.sp,
                                  fontWeight: FontWeight.w400),
                            ).clickOnce((){
                              isAllRecord=!isAllRecord;
                              update();
                            }),
                          ),
                        ],
                      ),
                      isAllRecord? Container(
                        padding: EdgeInsets.only(left: 10.w,right: 10.w),
                        margin: EdgeInsets.only(bottom: 2.w),
                        decoration: BoxDecoration(
                          color: Colors.white,
                          borderRadius: BorderRadius.circular(4.w),
                          border: Border.all(
                              color: const Color(0xff2267C0), width: 1.w),
                        ),
                        child: Column(children: [
                          CustomSelectPage(
                            selectText:supervisionRecord.isNotEmpty? supervisionRecord.first.superviseUserName:'',
                            title: '督办人：',
                            isRequired: false,
                            isEnabled: false,
                            onCallBack: () {},
                          ),
                          CustomSelectPage(
                            selectText:supervisionRecord.isNotEmpty?supervisionRecord.first.superviseObjName:'',
                            title: '督办对象：',
                            isEnabled: false,
                            isRequired: false,
                            isShowDivider: false,
                            onCallBack: () {},
                          ),
                        ],),
                      ):  Column(children:supervisionRecord.map((val)=>Container(
                        padding: EdgeInsets.only(left: 10.w,right: 10.w),
                        margin: EdgeInsets.only(bottom: 2.w),
                        decoration: BoxDecoration(
                          color: Colors.white,
                          borderRadius: BorderRadius.circular(4.w),
                          border: Border.all(
                              color: const Color(0xff2267C0), width: 1.w),
                        ),
                        child: Column(children: [
                          CustomSelectPage(
                            selectText:val.superviseUserName,
                            title: '督办人：',
                            isRequired: false,
                            isEnabled: false,
                            onCallBack: () {},
                          ),
                          CustomSelectPage(
                            selectText:val.superviseObjName,
                            title: '督办对象：',
                            isEnabled: false,
                            isRequired: false,
                            isShowDivider: false,
                            onCallBack: () {},
                          ),
                        ],),
                      )).toList(),),
                    ],),
                  ),
                  CustomSelectPage(
                    selectText: UserManager.getUser()!.nickname,
                    title: '督办人：',
                    isRequired: false,
                    isEnabled: false,
                    onCallBack: () {},
                  ),
                  CustomSelectPage(
                    selectText:
                    controller.onSiteHandlerName,
                    title: '督办对象：',
                    isRequired: false,
                    isShowDivider: false,
                    onCallBack: () {
                      Get.to(()=>CommonSelectionPage<SystemUserPageEntity>(title: '督办对象', enableLoad: false), arguments: {
                        'interfaceUrl': Interface.getSupervisorList,
                        'queryParameters': {'type':item.supervisionStatusStr,'level':item.alarmLevel,'companyId':item.companyId},// 等级 1,2,3,4  红橙黄蓝对应   等级非必传   督办处置的时候才传  但也可以都传 不影响
                      })?.then((value) {
                        //如果不为空则设置信息
                        if (value != null) {
                          final List<SystemUserPageEntity>selectedList = value as List<SystemUserPageEntity>;
                          controller.onSiteHandlerId = selectedList[0].id; //获取人员id
                          controller.onSiteHandlerName = selectedList[0].nickname!; //获取人员名字
                          controller.update();
                        }
                      });
                    },
                  ),
                ],
              );
            }),
        func: (b) {
          if (b) {
            //调接口去督办 /system/alarm-supervise-info/create
            alarmSuperviseInfoCreate(item,closeOverlays:closeOverlays );
          }
        },
      ),barrierDismissible: false);
    } else if (item.supervisionStatusStr == '3') {
      // } else if (true) {
      // 弹窗提示
      Get.dialog<bool>(CommonAdaptiveDialog(
        title: '派发',
        contentWidget:
        GetBuilder<TodayController>(
          builder: (controller) {
            return Column(
              children: [
                CustomSelectPage(
                  selectText: UserManager.getUser()!.nickname,
                  title: '派发人：',
                  isRequired: false,
                  isEnabled: false,
                  isShowDivider: false,
                  onCallBack: () {},
                ),
                CustomSelectPage(
                  isRequired: false,
                  isShowDivider: false,
                  selectText: controller .departmentBelongsIdName,
                  title: '处置人部门：',
                  onCallBack: () {
                    controller.selectCurrentDept2(item);
                  },
                ),
                CustomSelectPage(
                  selectText: controller.affiliateCompanyAssignHighIdName,
                  title: '处置人：',
                  isRequired: false,
                  isShowDivider: false,
                  onCallBack: () {
                    controller.selectCurrentDept3();
                  },

                ),

              ],
            );
          },
        ),
        func: (b) {
          if (b) {
            //派发
            alarmSuperviseInfoCreate(item,closeOverlays:closeOverlays );
          }
        },
      ),barrierDismissible: false);
    } else  {
      // 弹窗提示
      Get.dialog<bool>(CommonAdaptiveDialog(
        title: '处置',
        contentWidget:
        GetBuilder<TodayController>(
          builder: (controller) {
            return Column(
              children: [
                CustomSelectPage(
                  selectText: UserManager.getUser()!.nickname,
                  title: '处置人：',
                  isRequired: false,
                  isEnabled: false,
                  isShowDivider: false,
                  onCallBack: () {},
                ),
                CustomSelectPage(
                  selectText:DateTime.now().toStr,
                  title: '处置时间：',
                  isRequired: false,
                  isEnabled: false,
                  isShowDivider: false,
                  onCallBack: () {},
                ),
                CustomHighInputPage(
                  title: '报警原因',
                  text: controller.reasonAlarm,
                  hintText: '请输入报警原因',
                  onCallBack: (value) {
                    controller.reasonAlarm = value;
                  },
                ),
                CustomHighInputPage(
                    title:'处置措施',
                    text: controller.alarmDescription,
                    hintText: '请输入处置措施',
                    onCallBack: (value) {
                      controller.alarmDescription = value;
                    }),
                CustomFileUploadPage(
                  type: FileType.custom,
                  isShowDivider: false,
                  splitCommaInUrl: true,
                  isRequired:false,
                  // uploadedFiles: [],
                  title: '处置附件',
                  onCallBack: (value) {
                    final String imgUrl = value.join(',');
                    disposalAttachments = imgUrl;
                  },
                ),
              ],
            );
          },
        ),
        func: (b) {
          if (b) {
            //处置
            alarmSuperviseInfoCreate(item,closeOverlays:closeOverlays );
          }
        },
      ),barrierDismissible: false);
    }
  }
  // 选中的责任部门
  CorporationNameEntity? selectIdDeptList;
  /// 选择完责任单位后,选择处置人部门
  void selectCurrentDept2(AlarmRespEntity item) async {
    final res = await HttpUtil()
        .generateGetRequest<List<CorporationNameEntity>>(
        Interface.mainBaseUrl + '/admin-api/system/dept/getByParent',
        queryParameters: {'parentId': item.companyId}).execute();
    if (res.isSucceed) {
      final List<CorporationNameEntity> list = res.data??[];
      list.insert(0, CorporationNameEntity(
        name:item.companyName,
        id:item.companyId,
        createTime: 0,
        email: '',
        flag: 0,
        leaderUserId: 0,
        parentId: 0,
        sort: 0,
        status: 0,
        phone: '',
      ));
      CustomEquipmentBottomSheet<CorporationNameEntity>(
        dataList: list,
        isMultiple: false,
        checkedList: selectIdDeptList != null ? [selectIdDeptList!] : [],
        onConfirm: (value) {
          if (value.isNotEmpty) {
            selectIdDeptList = value[0];
            departmentBelongsId = value[0].getId(); //部门id
            departmentBelongsIdName = value[0].getShowName(); //部门
            update();
          }
        },
        title: '处置人部门',
      ).showBottomSheetDialog();
    }
  }

  // 选中的责任人
  DepartmentUserEntity? selectIdPersonList;

  /// 选完责任部门后,根据选择的部门去拿处置人
  void selectCurrentDept3() async {
    if (departmentBelongsId.isEmpty) {
      AppToast.show('处置人部门');
      return;
    } else {
      // 获取 selectIdDeptList 的所有id,用,号拼起来
      // final String deptId = selectIdDeptList.map((e) => e.id).join(',');
      final res = await HttpUtil()
          .generateGetRequest<List<DepartmentUserEntity>>(
          '${Interface.mainBaseUrl}/admin-api/system/user/getListByDeptIds',
          queryParameters: {
            'deptId': selectIdDeptList?.id,
          }).execute();
      if (res.isSucceed) {
        final List<DepartmentUserEntity> list = res.data!;
        CustomEquipmentBottomSheet<DepartmentUserEntity>(
          isMultiple: false,
          dataList: list,
          // checkedList: selectIdPersonList ?? [],
          checkedList: selectIdPersonList != null ? [selectIdPersonList!] : [],
          onConfirm: (value) {
            if (value.isNotEmpty) {
              selectIdPersonList = value[0];
              affiliateCompanyAssignHighId = value[0].getId(); //获取人员id
              affiliateCompanyAssignHighIdName =
                  value[0].getShowName(); //获取人员名字
              update();
            }
          },
          title: '选择处置人',
        ).showBottomSheetDialog();
      }
    }
  }
  /// 老版本处置时的提交（处置消警操作）
  Future<void> chuZhiConfirm(AlarmRespEntity item) async {
    // 附件信息
    final res = await HttpUtil().generatePutRequest(
      Interface.putDisposeAlarm,
      data: {
        'id': item.id,
        // 'type': 2,
        'reasonType': reasonAlarm, //报警原因
        'reasonAnalysis': alarmDescription, //报警描述
        'description': disposalMeasures, //处置措施
        'disarmingDescriptionAnnex': disposalAttachments, //附件
      },
    ).execute(isShowLoading: true);
    res.onSuccess((result) {
      AppToast.showSuccess('处置成功!');
    });
  }

  /// 进入详情页面
  void goDetails( AlarmRespEntity entity) {
    //详情
    Get.toNamed(Routes.alarmDetailPage, arguments: entity)?.then((value) {
      // if (value != null) {
      //   globalKey.currentState?.onRefresh();
      // }
    });
  }

}
